

import 'dart:convert';
import 'package:xim/common/util/collection.dart';
import 'package:xim/common/util/security.dart';
import 'package:xim/http/apis/secret/secret_model.dart';
import 'package:xim/http/apis/session/session_api.dart';
import 'package:xim/http/apis/user/user_api.dart';
import 'package:xim/http/ase.dart';
import 'package:xim/http/http.dart';
import 'package:xim/http/rsa.dart';
import 'package:xim/http/store.dart';

/// 密钥API
class SecretApi {

  /// 创建会话密钥
  static Future<int> requestCreateSessionSecretKeys(int sessionId, List<SecretKeyVo> data) async{
    Map<String, Object> requestData = {
      "preSecretKeyVersion": -1 ,
      "sessionId": sessionId,
      "secretItems": data,
    };
    var respData = await dio.postResult("/store/secret/create", data: json.encode(requestData));
    return respData.data as int;
  }

  /// 获取会话的ASE密钥（最新的ASE密钥）
  static Future<SessionSecretKeyModel?> queryLatestSessionSecretKey(int sessionId) async {
    var respData = await dio.postResult("/store/secret/query", queryParameters: {"sessionId": sessionId});
    if(respData.data==null){
      return null;
    }
    return SessionSecretKeyModel.fromJson(respData.data);
  }

  /// 获取会话的ASE密钥
  static Future<List<SessionSecretKeyModel>> querySessionSecretKeys(int sessionId) async {
    var respDataList = (await dio.postResult("/store/secret/query/list", queryParameters: {"sessionId": sessionId})).data as List;
    return respDataList.map((e) => SessionSecretKeyModel.fromJson(e)).toList();
  }

  /// 获取会话的ASE密钥
  static Future<SessionSecretKeyModel> querySessionSecretKeyById(int secretKeyId) async {
    var respData = (await dio.postResult("/store/secret/query/id", queryParameters: {"secretKeyId": secretKeyId}));
    return SessionSecretKeyModel.fromJson(respData.data);
  }

}

/// 创建会话密钥 Vo model
class SecretKeyVo {

  /// 加密后的会话密钥
  final String secretKey;

  /// 会话成员账号
  final String userAccount;

  SecretKeyVo(this.secretKey, this.userAccount);

  Map<String, dynamic> toJson()=> {
    "secretKey":secretKey,
    "userAccount":userAccount,
  };

}